package ext.tianma.number.util;

import java.io.FileInputStream;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Locale;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;

import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.generic.GenericType;
import wt.iba.value.service.LoadValue;
import wt.inf.container.WTContainerRef;
import wt.lifecycle.LifeCycleState;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.org.WTPrincipal;
import wt.part.QuantityUnit;
import wt.part.Source;
import wt.part.WTPart;
import wt.pom.Transaction;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.views.View;
import wt.vc.views.ViewException;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;

public class UpdatePart implements RemoteAccess, Serializable{	
	private static Locale locale = null;
	private static String CLASSNAME = UpdatePart.class.getName();
	private static boolean VERBOSE = false;
	static {
		try {
			VERBOSE = (WTProperties.getLocalProperties()).getProperty("ext.tianma.excel.verbose", false);
			locale = SessionHelper.manager.getLocale();
		} catch (Throwable throwable) {
			throw new ExceptionInInitializerError(throwable);
		}
	}
	
	/**
	 * 通过电子表格导入物料
	 * @throws WTException 
	 * 
	 */
	public static void doImportFillPart(String fileContent ,WTContainerRef containerRef) throws WTException{
		Hashtable IBAHashTable = new Hashtable();
		Hashtable valuesTable = new Hashtable();
		IBAHashTable.clear();
		HSSFWorkbook wb = null;
        FileInputStream fis = null;
        Transaction trx = new Transaction(); 
        WTPrincipal curUser =SessionHelper.manager.getPrincipal();
        
        try {
        	trx.start();
        	System.out.println("进入方法体中！事物开启");
            fis = new FileInputStream(fileContent);
            wb = new HSSFWorkbook(fis);
            HSSFSheet sheet = wb.getSheetAt(0);    
			System.out.println("sheet》》》》》》》》》="+sheet);
            if(sheet == null){
            	throw new WTException("导入文件中的表格不能为空!");
            }
            HSSFRow rows = sheet.getRow(5);                                    
            System.out.println("查看有多少行数>>>>>>>>>>>>>>"+sheet.getLastRowNum());
            for(int i=6;i<sheet.getLastRowNum()+1;i++) {      
            	HSSFRow row = sheet.getRow(i);							   
            	HSSFCell cellNumber = row.getCell(1);								   
            	HSSFCell cellView = row.getCell(9);								   
            	String number = getCellValue(cellNumber);
            	if(number.equals("") || number ==null)
            			throw new WTException("导入电子表格时编号不能为空!");
            	String view = getCellValue(cellView);
            	checkView(view);
            	WTPart part = CoreUtil.getWTPartByNumberAndView(number, view); 
            	WTPart deignPart = PartUtil.getWTPartByNumber(number);
            	System.out.println("part ="+part);
            	for (int j = 0; j < rows.getLastCellNum(); j++) {
            		String partNumber =getCellValue(row.getCell(j));
            		System.out.println("《《《《《《《《《《，partNumber="+partNumber);
            		if(partNumber==null){
            			partNumber="";
            		}
            		String partIBA =getCellValue(row.getCell(j+14));
            		System.out.println("《《《《《《《《《《，partIBA="+partIBA);
            		if(partIBA==null){
            			partIBA="";
            		}
            		valuesTable.put(getCellValue(rows.getCell(j)), partNumber);  
            		IBAHashTable.put(getCellValue(rows.getCell(j+14)), partIBA);
				}
            	if(part == null && deignPart == null)
            		createPart(valuesTable, containerRef, IBAHashTable);     
            	else if(part!=null){
            		Folder folder =null;
            		String file = valuesTable.get("Location").toString();
            		if(file.equals("") || file == null)
            			throw new WTException("导入电子表格时存放路径不能为空!");
            		String partView = part.getViewName();
            		String state =valuesTable.get("State").toString();	
            		String partState =part.getState().toString();
            		SessionHelper.manager.setAdministrator();
            		if(partView.equals(view)){	
            			initializeWTPart(valuesTable, part,folder, 0);		 
            		    if(!partState.equals(state)){
            		    	State st=State.toState(state);
                			LifeCycleState ls= new LifeCycleState();
                			ls.setState(st);
                			part.setState(ls); 
            		    }
            			PersistenceServerHelper.manager.update(part);
            			part = (WTPart) PersistenceHelper.manager.refresh(part);
            			setIBAWTPart(part,IBAHashTable);
            		}else if(!partView.equals(view)){
            			WTPart newpart=null;
            			//根据最新版本对象创建视图
            			WTPart newNumberPart= PartUtil.getWTPartByNumber(number);                                 
            			newpart = (WTPart)ViewHelper.service.newBranchForView(newNumberPart, view);
            			newpart=(WTPart)PersistenceHelper.manager.save(newpart);
        				newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);
        				
//            			if(partView.equals("Design")){
//            				newpart=(WTPart)ViewHelper.service.newBranchForView(part, view);
//            				System.out.println("<<<<<<<<<<<<<<<view="+newpart.toString());
//            				newpart=(WTPart)PersistenceHelper.manager.save(newpart);
//            				newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);
//	
//            			}else if(!partView.equals("Design")){
//            				part=(WTPart)CoreUtil.getWTPartByNumberAndView(number,"Design");
//            				newpart=(WTPart)ViewHelper.service.newBranchForView(part, view);
//            				System.out.println("<<<<<<<<<<<<<<<view="+newpart.toString());
//            				newpart=(WTPart)PersistenceHelper.manager.save(newpart);
//            				newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);
//            			}            			
            			
            			initializeWTPart(valuesTable, newpart,folder, 0);            				
            			PersistenceServerHelper.manager.update(newpart);
            			if(!partState.equals(state)){
            		    	State st=State.toState(state);
                			LifeCycleState ls= new LifeCycleState();
                			ls.setState(st);
                			newpart.setState(ls); 
            		    }
            			newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);
            			setIBAWTPart(newpart,IBAHashTable);
            		}
            	}else if(part == null && deignPart != null){
            		Folder folder =null;
            		String file = valuesTable.get("Location").toString();
            		if(file.equals("") || file == null)
            			throw new WTException("导入电子表格时存放路径不能为空!");
            		String partView = deignPart.getViewName();
            		String state =valuesTable.get("State").toString();	
            		String partState =deignPart.getState().toString();
            		
            		if(partView.equals(view)){
            			initializeWTPart(valuesTable, deignPart,folder, 0);		 
            		    if(!partState.equals(state)){
            		    	State st=State.toState(state);
                			LifeCycleState ls= new LifeCycleState();
                			ls.setState(st);
                			deignPart.setState(ls); 
            		    }
            			PersistenceServerHelper.manager.update(deignPart);
            			deignPart = (WTPart) PersistenceHelper.manager.refresh(deignPart);
            			setIBAWTPart(deignPart,IBAHashTable);
            			
            		}else if(!partView.equals(view)){
            			WTPart newpart=null;
                		newpart = (WTPart)ViewHelper.service.newBranchForView(deignPart, view);
                		newpart=(WTPart)PersistenceHelper.manager.save(newpart);
                		newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);
                		
                		initializeWTPart(valuesTable, newpart,folder, 0);            				
            			PersistenceServerHelper.manager.update(newpart);
            			if(!partState.equals(state)){
            		    	State st=State.toState(state);
                			LifeCycleState ls= new LifeCycleState();
                			ls.setState(st);
                			newpart.setState(ls); 
            		    }
            			newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);
            			setIBAWTPart(newpart,IBAHashTable);
            		}
        		}
			} 
            trx.commit();
            trx = null;
		} catch (Exception e) {
			e.printStackTrace();
			throw new WTException(e.getMessage());
		}finally{
			SessionHelper.manager.setPrincipal(curUser.getName());
            if(trx!=null){
            	trx.rollback();
                System.out.println("	导入出错，数据回滚.");
            }
		}
	}


	/**
	 *创建零部件或物料
	 * @param number
	 * @param name
	 * @param partTypeStr
	 * @param sourceStr
	 * @param viewStr
	 * @param defaultUnitStr
	 * @param folder
	 * @param container
	 * @return
	 * @throws WTException
	 */
	public static WTPart createPart(Hashtable table , WTContainerRef containerRef , Hashtable IBAValues) throws WTException{
	    WTPart part = null;
	    part = WTPart.newWTPart();
	    String file = table.get("Location").toString();
	    Folder folder = getFolderByContainerRef(file, containerRef);	    
	    part = initializeWTPart(table , part , folder , 1);
	    part = (WTPart) PersistenceHelper.manager.store(part);
	    String state =table.get("State").toString();
	    WorkflowUtil.setLifeCycleState(part, state); 
	    setIBAWTPart(part,IBAValues);
	    return part;
	}
	
	/**
     * 初始化零部件
     * @param part 零部件
     * @param number			编码
     * @param name				名称
     * @param partTypeStr		零部件类型(装配模式)
     * @param sourceStr		来源
     * @param viewStr		视图
     * @param defaultUnitStr	单位
     * @param folder		文件夹
     * @param container		容器
     * @return
     * @throws WTException
     */
    public static WTPart initializeWTPart(Hashtable table , WTPart part ,Folder folder ,int i) throws WTException{
        String partType = null;
        ViewReference viewRef = null;
        QuantityUnit defaultUnit = null;
        Source source = null;
        boolean bool= false;
        String partName=table.get("Name").toString();
        try
        {
            partType = table.get("Type").toString();          
            defaultUnit = QuantityUnit.toQuantityUnit(table.get("Default Unit").toString());
            source = Source.toSource(table.get("Source").toString());
            viewRef = getViewRef(table.get("View").toString());
            if(partName.equals("") || part == null)
            	throw new WTException("导入电子表格时名称不能为空!");
            if(i==1){
            	LoadValue.setType(part, partType);
            	part.setNumber(table.get("Number").toString());
            	part.setName(partName);
            	part.setView(viewRef); 
            }
            String endItem = table.get("End Item").toString();
            if(endItem.equals("true")){
            	bool =true;
            }          
            part.setEndItem(bool);                    
            GenericType gt= GenericType.toGenericType(table.get("Generic Type").toString());
            part.setGenericType(gt);

            part.setSource(source);
            part.setDefaultUnit(defaultUnit);
       
            if (folder != null && i==1)
            {
                FolderHelper.assignLocation(part, folder);
            }
        }
        catch (Exception exception)
        {
            throw new WTException(exception);
        }
        return part;
    }
    
    /**
     * 设置生成对象的IBA属性
     * @param part 对象
     * @param table  IBA属性值映射表(key=逻辑标识符;value=属性值)
     * @throws WTException 
     */
    public static void setIBAWTPart(WTPart part ,Hashtable table) throws WTException{
    	IBAUtil.setSoftTypeIBAValues(part, table);	
    }
    

    /**
     *根据视图名称获取视图对象
     * @param viewStr
     * @return
     * @throws WTException
     */
    public static ViewReference getViewRef(String viewStr) throws WTException{
    	if(viewStr.equals("") || viewStr == null)
    		throw new WTException("导入电子表格时视图不能为空!");
        ViewReference viewRef = null;
        View view = ViewHelper.service.getView(viewStr);
        if(view == null){
        	throw new WTException("电子表格中的"+viewStr+"不存在！");
        }
        viewRef = ViewReference.newViewReference(view);
        return viewRef;
    }
    
    /**
     *根据容器以及路径获取文件夹
     * @param location
     * @param wtcontainerref
     * @return
     * @throws WTException
     */
    public static Folder getFolderByContainerRef(String location, WTContainerRef wtcontainerref) throws WTException{
    	if(location.equals("") || location == null)
    		throw new WTException("导入电子表格时存放路径不能为空!");
        Folder folder = null;
        try {
        	folder = FolderHelper.service.getFolder(location, wtcontainerref);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(folder==null){
			throw new WTException("文件夹不存在！");
		}
        return folder;
    }
    
    /**
	 * 获取单元格中的信息
	 * 
	 * @param cell
	 *            单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Integer.toString((int)cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
					// TODO: handle exception
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}
		System.out.println("excel 单元格的值："+value);
		return value;
	}
	
	/**
	  * 判断输入的视图是否存在
	  * @param view 视图名称
	 * @throws WTException 
	 * @throws ViewException 
	  */
	 public static void checkView(String view) throws ViewException, WTException{
		 if(view.equals("") || view == null)
			 	throw new WTException("导入电子表格时视图不能为空！");
		//根据视图名称,获取视图对象
		View viewObj=null;
		try {
			viewObj = ViewHelper.service.getView(view);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(viewObj==null){
			throw new WTException("当前"+view+"视图对象不存在!");
		}
	 }
}
